package com.example.diningorder.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.diningorder.mapper.OrdersMapper;
import com.qf.pojos.*;
import com.qf.service.AddressBookService;
import com.qf.service.OrderDetailService;
import com.qf.service.OrdersService;
import com.qf.service.ShoppingCartService;
import com.qf.utils.PayUtils;
import com.qf.utils.SnowflakeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    //远程注入
    @Reference
    private ShoppingCartService shoppingCartService;

    //远程注入
    @Reference
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

//    @Value("${pay.natGo}")
    private String natGo;

    @Override
    @Transactional
    public R submit(Map map, HttpServletResponse resp) throws AlipayApiException, IOException {
        String uid = "1628997479305437185";

        List<ShoppingCart> shoppingCarts = shoppingCartService.listByUid(uid);

        if (shoppingCarts == null || shoppingCarts.size() == 0){
            return R.error("请先添加商品");
        }

        //生成订单
        Orders orders = new Orders();
        //设置订单号，唯一
        orders.setNumber(new SnowflakeUtils().nextId() + "");
        orders.setStatus(1);
        orders.setUserId(Long.parseLong(uid));
        Long addressBookId = Long.parseLong(map.get("addressBookId").toString());
        orders.setAddressBookId(addressBookId);
        orders.setOrderTime(new Date());
        orders.setPayMethod(Integer.parseInt(map.get("payMethod").toString()));

        //设置支付金额
        //获取当前登录用户的购物车数据
        BigDecimal amount = new BigDecimal(0);

        for (ShoppingCart shoppingCart : shoppingCarts) {
            BigDecimal dishAmount = shoppingCart.getAmount();
            Integer number = shoppingCart.getNumber();
            //每个菜品的金额
            BigDecimal multiply = dishAmount.multiply(new BigDecimal(number));

            //将所有菜品金额进行累加
            amount = amount.add(multiply);
        }
        log.info("购物车总金额为：{}",amount.doubleValue());
        orders.setAmount(amount);

        //设置备注信息
        orders.setRemark(map.get("remark").toString());
        //设置地址信息(远程获取地址信息 -- 地址管理服务)
        AddressBook addressBook = addressBookService.getById(addressBookId);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());

        //设置结账时间（不合理，应该是在支付完成后，更新这个时间）
        orders.setCheckoutTime(new Date());

        //保存
        save(orders);

        //生成订单详情
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //每个购物车数据都是一个订单详情项
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //设置订单id
            orderDetail.setOrderId(orders.getId());
            //利用自己的算法生成
            orderDetail.setId(null);
            orderDetails.add(orderDetail);
        }
        //批量插入
        orderDetailService.saveBatch(orderDetails);

        //清空购物车(清除当前下单用户的购物车数据)
        shoppingCartService.removeByUid(uid);

        //发起支付(① 支付的成功与否，不影响订单数据的入库 ② 这个支付操作可以在子线程中完成)
//        pay(resp,orders);

        System.out.println("订单数据生成，发起支付....");

        return R.success("下单成功");
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void pay(HttpServletResponse resp, Orders orders) throws AlipayApiException, IOException {
        PayUtils.pay(natGo,resp,orders);
    }
}
